package com.qqt.csr.archive.service.listener;

import cn.hutool.json.JSONUtil;
import com.qqt.csr.archive.batch.task.ArchiveRunner;
import com.qqt.csr.archive.entity.reader.ArtificialConversation;
import com.qqt.csr.archive.entity.reader.SmartConversation;
import com.qqt.csr.archive.entity.reader.SmartMessage;
import com.qqt.csr.archive.entity.writer.ArchiveConversation;
import com.qqt.csr.archive.entity.writer.ArchiveMessage;
import com.qqt.csr.archive.model.ConversationEndMessage;
import com.qqt.csr.archive.model.SmartChangeMessage;
import com.qqt.csr.archive.service.*;
import com.qqt.csr.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: yang hao
 * @Date: 2024/11/19 10:08
 * @Description: 会话结束事件监听
 **/
@Slf4j
@Service
@SuppressWarnings("unused")
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}" + "_" + "smart_change",
        topic = "archive_event_topic",
        selectorType = SelectorType.TAG,
        selectorExpression = "smart_change",
        messageModel = MessageModel.CLUSTERING,
        tlsEnable="${rocketmq.consumer.tlsEnable}"
)
public class SmartChangeEventListener implements RocketMQListener<SmartChangeMessage> {

    @Autowired
    private SmartMessageService smartMessageService;
    @Autowired
    private ArchiveMessageService archiveMessageService;

    @Override
    public void onMessage(SmartChangeMessage message) {
        // 校验会话结束通知消息
        List<ArchiveMessage> messages = archiveMessageService.findByMsgId(message.getMessageId());
        if (messages == null || messages.isEmpty()) {
            log.error("消息校验不通过，消息:{}", JsonUtil.toJson(message));
            return;
        }
        // 查询更新到扩展字段
        SmartMessage smartMessage = smartMessageService.getById(message.getMessageId());
        messages.forEach(archiveMessage -> archiveMessage.setSmartExt(JSONUtil.toJsonStr(smartMessage)));
        archiveMessageService.save(messages);
    }


}
